package columbia.edu;

import java.io.*;
import java.sql.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class LoginAuthentication extends HttpServlet{

	private static final long serialVersionUID = 1L;
	//public void init(ServletConfig config) throws ServletException{}
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
	    PrintWriter out = response.getWriter();
	    HttpSession session = request.getSession(true);
	    if (session.isNew()){
	    	session.setAttribute("accessCount", 1); 
	    	System.out.println("This is a new session");
	    }else{
	    	System.out.println("Welcome back!");
	    }
	    	    
	    System.out.println("session id: " + session.getId());  
	    Integer accessCount = (Integer)session.getAttribute("accessCount"); 
	      if (accessCount != null) {
	         accessCount = new Integer(accessCount.intValue() + 1);
	      }  
	    session.setAttribute("accessCount", accessCount); 
	    System.out.println("accessCount" + accessCount);
	    
	    String connectionURL = "jdbc:oracle:thin:@//w4111b.cs.columbia.edu:1521/ADB";
	    Connection connection=null;
	    ResultSet rs;
	    
	    String username=null;
	    String passwrd=null;
	    String fname="Anonymous";
	    String lname="Anonymous";
	    response.setContentType("text/html");
	    try {
	       // Load the database driver
	      boolean foundUser=false;	
	      Class.forName("oracle.jdbc.pool.OracleDataSource");
	      // Get a Connection to the database
	      
	      connection = (Connection) request.getSession().getAttribute("Connection");
	      
	      if (connection == null) {
	    	  connection = DriverManager.getConnection(connectionURL, "ab3416", "kFxJssQk");
	    	  request.getSession().setAttribute("Connection",connection);
	      }

	      String sql = "select cust_id,pwd from customers ";
	      Statement s = connection.createStatement();
	      s.executeQuery (sql);
	      rs = s.getResultSet();
	      System.out.println("size="+rs.getFetchSize());
	      String userform = request.getParameter("user");
	      String passform = request.getParameter("pass"); 
	      
	      session.setAttribute("theName", userform);
	      session.setAttribute("thePass", passform);
	      
	      System.out.println("userName from jsp="+userform );
	      System.out.println("pass from jsp="+ passform);
	      
	      while (rs.next ()){
	        username=rs.getString("cust_id").trim();
	        passwrd=rs.getString("pwd").trim();
	        
	        System.out.println("username from data="+ username);
	        System.out.println("password from data="+ passwrd);
	        System.out.println("for user="+username.equals(request.getParameter("user")));
	        System.out.println("for pass="+passwrd.equals(request.getParameter("pass")));
	        
	        if(username.equals(request.getParameter("user").trim()) && passwrd.equals(request.getParameter("pass"))){
	        	
	        	String query = "select fname, lname from customers where cust_id LIKE ?";
				PreparedStatement s1 = connection.prepareStatement(query);
	            s1.setString(1,"%" + userform + "%"); // set input parameter
	            ResultSet rs1 = s1.executeQuery();
	            System.out.println("size="+rs1.getFetchSize());

	            try {
					while (rs1.next()) {
						System.out.println("In while loop");
						fname=rs1.getString("fname");
						lname=rs1.getString("lname");
						System.out.println("fname from data="+ fname);
						System.out.println("lname from data="+ lname);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

	        	rs1.close();
	        	s1.close();
	        	request.setAttribute("fname", fname.toUpperCase() );
	        	request.setAttribute("lname", lname.toUpperCase() );

	            String nextJSP = "/index2.jsp";
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
				dispatcher.forward(request,response);
	            foundUser=true;
	            break;
	          }
	        
	      }
	      
	      rs.close ();
	      s.close ();
	     if(!foundUser){
	    	 out.println("Please enter correct username and password");
		     out.println("<a href='AuthenticLogin.jsp'><br>Login again</a>"); 
	     }
	      
	     }catch(Exception e){
	    	 System.out.println("Exception is ;"+e);
	     } 
	     finally {
	    	
			/*
	    	try {
			if (connection != null) connection.close();
			}
			catch (SQLException ignored){
			out.println(ignored);
			}
			*/
	     }
	  }
    
}   